import React, { useCallback } from 'react';
import { Card, Space, Typography, Tooltip, Button } from 'antd';
import { 
  PlayCircleOutlined,
  CheckCircleOutlined,
  BugOutlined
} from '@ant-design/icons';
import SqlEditor from '../SqlEditor/SqlEditor';
import { useAnalysisContext, useAnalysisActions } from '../../context/AnalysisContext';
import { performUnifiedAnalysis } from '../../services/api';
import { createEditorMarker } from '../SqlEditor/SqlEditor';
import { message } from 'antd';

const { Text } = Typography;

const SqlEditorSection: React.FC = () => {
  const { state } = useAnalysisContext();
  const actions = useAnalysisActions();

  const {
    sqlContent,
    sourceDbType,
    targetDbType,
    aiEnhancementEnabled,
    userId,
    editorMarkers,
    isAnalyzing,
    analysisResult,
    analysisConfig,
    cursorPosition
  } = state;

  // 执行分析
  const handleAnalysis = useCallback(async () => {
    if (!sqlContent.trim()) {
      message.warning('请先输入SQL语句');
      return;
    }

    if (sourceDbType === targetDbType) {
      message.info('源数据库和目标数据库相同，无需兼容性分析');
      return;
    }

    try {
      actions.setIsAnalyzing(true);
      actions.clearAnalysisResult();

      const request = {
        sqlContent,
        sourceDbType,
        targetDbType,
        aiEnhancementEnabled,
        userId,
        taskName: `Editor-Analysis-${Date.now()}`
      };

      const response = await performUnifiedAnalysis(request);

      if (response.data.success) {
        const result = response.data;
        actions.setAnalysisResult(result);

        // 创建编辑器标记
        const markers = result.issues?.map(issue => createEditorMarker(issue)) || [];
        actions.setEditorMarkers(markers);

        const issueCount = result.statistics?.totalIssues || 0;
        if (issueCount === 0) {
          message.success('分析完成，未发现兼容性问题');
        } else {
          message.success(`分析完成，发现 ${issueCount} 个兼容性问题`);
        }
      } else {
        message.error(response.message || '分析失败');
      }
    } catch (error: any) {
      console.error('分析失败:', error);
      message.error(error.message || '分析失败，请检查网络连接');
    } finally {
      actions.setIsAnalyzing(false);
    }
  }, [sqlContent, sourceDbType, targetDbType, aiEnhancementEnabled, userId, actions]);

  // 处理SQL内容变更
  const handleSqlChange = useCallback((content: string) => {
    actions.setSqlContent(content);
    
    // 实时分析
    if (analysisConfig.enableRealTimeAnalysis && content.trim()) {
      // 使用防抖处理
      const timeoutId = setTimeout(() => {
        handleAnalysis();
      }, analysisConfig.debounceDelay);
      
      return () => clearTimeout(timeoutId);
    }
  }, [actions, analysisConfig, handleAnalysis]);

  // 处理光标位置变化
  const handleCursorPositionChange = useCallback((line: number, column: number) => {
    actions.setCursorPosition({ line, column });
  }, [actions]);

  // 处理标记点击
  const handleMarkerClick = useCallback((marker: any) => {
    if (marker.issueId && analysisResult) {
      const issue = analysisResult.issues?.find(i => i.id === marker.issueId);
      if (issue) {
        actions.setSelectedIssueId(issue.id);
        actions.setCursorPosition({ line: issue.lineNumber, column: issue.columnNumber });
        message.info(`跳转到第 ${issue.lineNumber} 行：${issue.description}`);
      }
    }
  }, [analysisResult, actions]);

  // 计算统计信息
  const issueCount = editorMarkers.length;
  const errorCount = editorMarkers.filter(m => m.severity === 'error').length;
  const warningCount = editorMarkers.filter(m => m.severity === 'warning').length;

  // 渲染标题栏
  const renderTitle = () => (
    <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
      <Space>
        <span>SQL编辑器</span>
        {issueCount > 0 && (
          <Space size={4}>
            {errorCount > 0 && (
              <Tooltip title={`${errorCount} 个错误`}>
                <span style={{ color: '#ff4d4f', fontSize: '12px' }}>
                  <BugOutlined /> {errorCount}
                </span>
              </Tooltip>
            )}
            {warningCount > 0 && (
              <Tooltip title={`${warningCount} 个警告`}>
                <span style={{ color: '#faad14', fontSize: '12px' }}>
                  ⚠ {warningCount}
                </span>
              </Tooltip>
            )}
          </Space>
        )}
        {issueCount === 0 && sqlContent.trim() && (
          <Tooltip title="没有发现问题">
            <span style={{ color: '#52c41a', fontSize: '12px' }}>
              <CheckCircleOutlined />
            </span>
          </Tooltip>
        )}
      </Space>

      <Space size={4}>
        {/* 分析按钮 */}
        {!analysisConfig.enableRealTimeAnalysis && (
          <Button
            type="primary"
            icon={<PlayCircleOutlined />}
            onClick={handleAnalysis}
            loading={isAnalyzing}
            size="small"
            disabled={!sqlContent.trim() || sourceDbType === targetDbType}
          >
            {aiEnhancementEnabled ? 'AI增强分析' : '规则分析'}
          </Button>
        )}

        {/* 当前光标位置 */}
        <Text type="secondary" style={{ fontSize: '12px' }}>
          行 {cursorPosition.line}, 列 {cursorPosition.column}
        </Text>
      </Space>
    </div>
  );

  return (
    <Card 
      className="editor-section"
      title={renderTitle()}
      size="small"
    >
      <SqlEditor
        value={sqlContent}
        onChange={handleSqlChange}
        height={500}
        theme="vs-light"
        markers={editorMarkers}
        onMarkerClick={handleMarkerClick}
        onCursorPositionChange={handleCursorPositionChange}
        showLineNumbers={analysisConfig.showLineNumbers}
        enableFormatting={true}
        readOnly={false}
      />
    </Card>
  );
};

export default SqlEditorSection;